import { Button, Flex, Select } from "antd";
import { useEffect, useState } from "react";
import { serialPort } from "../service/SerialPort";
import { runProg } from "../service/run";
import { ping } from "../service/service";

export default function SerialPortSetting() {

	const [ports, setPorts] = useState<string[]>(['12', '2']);
	const [port, setPort] = useState('');
	const [openText, setOpenText] = useState('打开');

	const update = async () => {
		const ps = await serialPort.activePorts();
		setPorts(ps);
		if (ps.length != 0) {
			setPort(ps[0]);
		}
	};

	const init = async () => {
	
		if (await serialPort.isOpen()) {
			setOpenText('关闭');
		} else {
			setOpenText('打开');
		}

	};

	const onClickRefresh = async () => {
		runProg('刷新串口', async () => {
			const ps = await serialPort.activePorts();
			setPorts(ps);
		});
	};

	const onClickOpen = async () => {
		runProg('打开/关闭串口', async () => {
			if (await serialPort.isOpen()) {
				await serialPort.close();
			} else {
				if (port.length == 0) {
					throw '没有选择串口';
				}	
				await serialPort.open(port);
			}
			await init();
		});
	};

	async function onClickPing() {
		runProg('ping', async () => {
			await ping();
		});
	}

	useEffect(() => {
		init();
		update();
	}, []);

	return (
		<Flex vertical={true} gap={5} className="card m10">
			<label style={{ fontSize: '20px', alignSelf: 'center' }}>串口设置</label>
			<Flex vertical={false} gap={5} align={"center"}>
				<label>端口:</label>
				<Select value={port} style={{ width: '100px' }} onChange={(item) => setPort(item)}>
					{
						ports.map((item, index) => (<Select.Option key={index}>{item}</Select.Option>))
					}
				</Select>
				<Button onClick={onClickRefresh} type={"primary"}>刷新</Button>
			</Flex>
			<Flex vertical={false} gap={5}>
				<Button onClick={onClickOpen} type={"primary"}>{openText}</Button>
				<Button onClick={onClickPing}>Ping</Button>
			</Flex>
			
		</Flex>
	)
}
